<!-- 车辆维修 -->
<template>
  <div class="page-container">
    <div class="quick-search">
      <div
        v-for="(item, index) in quickSearchData"
        :key="index"
        class="quick-search-item"
        :class="[item.checked ? 'quick-search-item-checked' : '']"
        @click="quickSearchClick(item)"
      >
        <div class="quick-search-item-label">{{ item.label }}</div>
        <div class="quick-search-item-value">{{ item.value + ' 单' }}</div>
      </div>
    </div>
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" @reset="handleReset" />
    <table-index :table="table" @loadData="loadData">
      <template #table-summary>
        <div class="table-info">
          <span class="table-info-item">
            未支付金额：<span class="num">{{ unitVal(objectField?.unpayTotalAmount, '元') }}</span>
          </span>
          <span class="table-info-item">
            已支付金额：<span class="num">{{ unitVal(objectField?.payedTotalAmount, '元') }}</span>
          </span>
          <span class="table-info-item">
            对账金额：<span class="num">{{ unitVal(objectField?.settlementTotalAmount, '元') }}</span>
            <a-tooltip content="仅统计支付状态为已支付的账单的对账金额">
              <icon-exclamation-circle style="font-size: 16px; color: #165dff; margin-left: 5px" />
            </a-tooltip>
          </span>
        </div>
      </template>
      <!-- 费用明细 -->
      <template #feeList="{ record }">
        <div v-for="(item, index) in record.feeList" :key="index">
          <span>{{ item.feeName }}：</span>
          <span>{{ item.feeActiveAmount }}元</span>
          <div class="td-divider" v-if="index != record.feeList.length - 1"></div>
        </div>
      </template>
      <!-- 业务单信息 -->
      <template #orderInfo="{ record }">
        <div v-if="record.refCode || record.channelOrderCode">
          <div class="order-info-item">
            <div>自有单号</div>
            <a-link class="order-info-item a-link" @click="() => toOrderDetail(record)">
              {{ record.refCode }}
            </a-link>
          </div>
          <div class="order-info-item" v-if="record.channelOrderCode">
            <div>{{ record.channelTypeName }}</div>
            <a-link v-if="record.channelOrderCode" class="order-info-item a-link" @click="() => toOrderDetail(record, 'channel')">
              {{ record.channelOrderCode }}
            </a-link>
          </div>
        </div>
        <div v-else> - </div>
      </template>
      <!-- 支付状态 -->
      <template #payStatus="{ record }">
        <div :class="['payStatus_' + record.payStatus]">{{ record.payStatusName }}</div>
      </template>
      <!-- 账单号 -->
      <template #billCode="{ record }">
        <div>{{ record.billCode || '-' }}</div>
        <div v-if="record.outBillCode"> <tag type="primary">外部</tag>{{ record.outBillCode }} </div>
      </template>
      <!-- 收支方式 -->
      <template #payTypeName="{ record }">
        <div>{{ record.payTypeName }}</div>
        <div v-if="record.payType == -1">{{ record.settlementBodyName }}</div>
      </template>
    </table-index>
  </div>
</template>

<script setup name="tripartitePaymentList">
  import { unitVal } from '@/utils'
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { getList, exportThirdPayment, getStatistics, getAccountByWayAndType } from '@/api/finance/thirdPayment'
  import { useExport } from '@/hooks/list'
  import { usePermission } from '@/hooks/usePermission'
  import useNavigate from '@/hooks/useNavigate'

  const route = useRoute()
  const { navigateTo } = useNavigate()
  const dict = usePageDict('thirdPaymentBillDict')
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '账单号', prop: 'billCodeOrOutLike', type: 'a-input' },
      { label: '业务单号', prop: 'refCodeLike', type: 'a-input' },
      { label: '客户名称', prop: 'customerNameLike', type: 'a-input' },
      {
        label: '支付状态',
        prop: 'payStatusList',
        type: 'a-select',
        options: dict.payStatusEnum,
        attrs: {
          multiple: true,
        },
      },
      {
        label: '结算方式',
        prop: 'payType',
        type: 'a-select',
        options: dict.payTypeEnum,
        change: (value) => {
          typeChange(value)
        },
      },
      {
        label: '结算主体',
        prop: 'settlementBodyId',
        type: 'a-select',
        placeholder: '请先选择结算方式',
        disabled: queryParam.payType == undefined,
        options: accountList.value,
      },
      {
        label: '业务类型',
        prop: 'bizType',
        type: 'a-select',
        options: dict.bizTypeEnum,
      },
      {
        label: '所属门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_listBystaff',
          popupContainer: '.modal-dialog-wrapper .remote-select-wrapper',
        },
      },
      {
        label: '交易完成时间',
        prop: 'finishDate',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        change: (value = []) => {
          queryParam.finishTimeBegin = value[0]
          queryParam.finishTimeEnd = value[1]
        },
      },
      {
        label: '账单生成时间',
        prop: 'createDate',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        change: (value = []) => {
          queryParam.createTimeBegin = value[0]
          queryParam.createTimeEnd = value[1]
        },
      },
    ]
  })
  const accountList = ref([])
  // 账号
  const typeChange = (e) => {
    if (e == '' || e == undefined) {
      accountList.value = []
      queryParam.settlementBodyId = undefined
      return
    }
    getAccountByWayAndType({ way: e, type: 0 }).then(({ result }) => {
      result.forEach((item) => {
        item.label = item.bank
        item.value = item.account
      })
      accountList.value = result
    })
  }

  const quickSearchData = ref([
    {
      key: -1,
      label: '全部账单数',
      value: 0,
      prop: 'totalCount',
      checked: true,
    },
    {
      key: 0,
      label: '未支付账单数',
      value: 0,
      prop: 'unpayCount',
      checked: false,
    },
    {
      key: 1,
      label: '已支付账单数',
      value: 0,
      prop: 'payedCount',
      checked: false,
    },
    {
      key: 9,
      label: '已取消账单数',
      value: 0,
      prop: 'cancelCount',
      checked: false,
    },
  ])
  const defaultQueryParam = {
    createDate: undefined,
    finishDate: undefined,
    billCodeOrOutLike: undefined,
    refCodeLike: undefined,
    customerNameLike: undefined,
    payStatusList: undefined,
    payType: undefined,
    bizType: undefined,
    siteId: undefined,
    finishTimeBegin: undefined,
    finishTimeEnd: undefined,
    createTimeBegin: undefined,
    createTimeEnd: undefined,
    settlementBodyId: undefined,
  }
  const queryParam = reactive(defaultQueryParam)

  // table 配置
  const table = useTable({
    columns: [
      { title: '业务单号', slotName: 'orderInfo', width: 240 },
      { title: '所属门店', dataIndex: 'siteName', width: 150 },
      { title: '客户名称', dataIndex: 'customerName', width: 100 },
      { title: '账单金额(元)', dataIndex: 'totalAmount', width: 110 },
      { title: '支付状态', slotName: 'payStatus', width: 110 },
      { title: '交易完成时间', dataIndex: 'finishTime', width: 170 },
      { title: '操作人', dataIndex: 'createUserName', width: 80 },
      { title: '生成时间', dataIndex: 'createTime', width: 170 },
      { title: '费用明细', slotName: 'feeList', width: 180 },
      { title: '结算备注', dataIndex: 'remark', width: 140, ellipsis: true },
      { title: '结算方式', dataIndex: 'payTypeName', width: 110 },
      { title: '收支类型', dataIndex: 'costTypeName', width: 100 },
      { title: '业务类型', dataIndex: 'bizTypeName', width: 100 },
      { title: '账单号', slotName: 'billCode', width: 200 },
      { title: '承担费率', render: (record) => `${record.tenantRate}%`, width: 100 },
      {
        title: '手续费(元)',
        // 为付款预留，判断costType类型，展示-还是+
        render: (record) => `${record.poundageAmount > 0 ? (record.costType == 10 ? '-' : '') : ''}${record.poundageAmount}`,
        width: 110,
      },
      { title: '对账金额(元)', dataIndex: 'settlementAmount', width: 110 },
    ],
    buttons: [
      {
        label: '导出',
        type: 'primary',
        permission: 'svms:finance:tripartitePayment.export',
        method: () => {
          const params = Object.assign({}, queryParam, {
            bizCodeLike: queryParam.refCodeLike,
            settlementType: queryParam.payType,
          })
          useExport(exportThirdPayment, params)
        },
      },
    ],
  })

  const objectField = ref({
    unpayTotalAmount: '',
    payedTotalAmount: '',
    settlementTotalAmount: '',
  })
  // 列表接口调用
  const loadData = (page) => {
    getNumsApi()
    let fn = useFetchTableDataApi(table, queryParam, getList)
    fn(page).then((res) => {
      objectField.value = res.objectField
    })
  }

  const handleReset = () => {
    quickSearchData.value.forEach((ele) => {
      ele.checked = ele.key == -1
    })
  }
  //快捷查询
  const quickSearchClick = (item) => {
    // 清空
    Object.keys(queryParam).map((it) => (queryParam[it] = undefined))
    quickSearchData.value.forEach((ele) => (ele.checked = ele.key == item.key))
    queryParam.payStatusList = item.key >= 0 ? [item.key] : undefined
    loadData()
  }

  const getNumsApi = () => {
    getStatistics().then(({ code, result }) => {
      if (code == 200) {
        quickSearchData.value.forEach((item) => {
          item.prop in result && (item.value = result[`${item.prop}`])
        })
      }
    })
  }

  // 跳转业务单详情
  const toOrderDetail = (val, type) => {
    switch (+val.bizType) {
      // 短租
      case 1:
        usePermission('svms:order:short-order.detail') &&
          navigateTo(`/short-order/detail/${val.refId}`, `${type ? val.channelOrderCode : val.refCode}-${type ? '渠道详情' : '短租详情'}`)
        break
      // 长租
      case 2:
        usePermission('svms:order:long-order.detail') &&
          navigateTo(`/long-order/detail/${val.refId}`, `${type ? val.channelOrderCode : val.refCode}-${type ? '渠道详情' : '长租详情'}`)
        break
      // 违章
      case 3:
        usePermission('svms:asstes:operation:car-violation.detail') &&
          navigateTo(`/car-violation/detail/${val.refId}`, `${type ? val.channelOrderCode : val.refCode}-${type ? '渠道详情' : '违章详情'}`)
        break
    }
  }

  onMounted(() => {
    route.query.code && (queryParam.billCodeOrOutLike = route.query.code)
    loadData()
  })
</script>

<style lang="less" scoped>
  .item-content {
    display: flex;
  }

  .table-info {
    display: flex;
    align-items: center;
    .table-info-item {
      margin-right: 20px;
      span {
        color: #1890ff;
      }
    }
  }
  .quick-search {
    display: flex;
    margin-bottom: 20px;
  }
  .quick-search-item {
    width: 16%;
    height: 62px;
    padding: 9px 0 9px 16px;
    border-radius: 4px;
    opacity: 1;
    border: 1px solid #e5e8ef;
    position: relative;
    cursor: pointer;
    color: #1d2129;
    font-size: 20px;
    font-weight: 600;
  }
  .quick-search-item:hover {
    transform: scale(1.1);
    transition: transform 0.3s;
    position: relative;
    z-index: 999;
  }
  .quick-search-item-checked {
    background: #e8f3ff;
    border: 1px solid #1890ff;
    color: #1890ff;
  }
  .quick-search-item:nth-of-type(n + 2) {
    margin-left: 20px;
  }
  .quick-search-item-label {
    font-size: 12px;
    font-weight: 400;
    color: #4e5969;
  }
  .order-info-item + .order-info-item {
    margin-top: 10px;
  }

  .a-link {
    color: rgba(24, 144, 255, 1);
  }
  .payStatus {
    &_0 {
      color: #ff7d00;
    }
    &_1 {
      color: #00b42a;
    }
    &_9 {
      color: #86909c;
    }
  }
</style>
